<?php

namespace System\Lib;

/**
 * Description of File
 *
 * @author elton.schivei
 */
class File extends \System\Types\Object
{

    const FILE_READ_MODE = 0644;
    const FILE_WRITE_MODE = 0666;
    const DIR_READ_MODE = 0755;
    const DIR_WRITE_MODE = 0777;
    const FOPEN_READ = 'rb';
    const FOPEN_READ_WRITE = 'r+b';
    const FOPEN_WRITE_CREATE_DESTRUCTIVE = 'wb'; // truncates existing file data, use with care
    const FOPEN_READ_WRITE_CREATE_DESTRUCTIVE = 'w+b'; // truncates existing file data, use with care
    const FOPEN_WRITE_CREATE = 'ab';
    const FOPEN_READ_WRITE_CREATE = 'a+b';
    const FOPEN_WRITE_CREATE_STRICT = 'xb';
    const FOPEN_READ_WRITE_CREATE_STRICT = 'x+b';

    /**
     * @param string $file
     * @return bool
     */
    public static function IsReallyWritable($file)
    {
        // If we're on a Unix server with safe_mode off we call is_writable
        if (\DIRECTORY_SEPARATOR == '/' AND @\ini_get("safe_mode") == false)
        {
            return \is_writable($file);
        }

        // For windows servers and safe_mode "on" installations we'll actually
        // write a file then read it.  Bah...
        if (\is_dir($file))
        {
            $file = \rtrim($file, '/') . '/' . \md5(\mt_rand(1, 100) . \mt_rand(1, 100));

            if (($fp = @\fopen($file, self::FOPEN_WRITE_CREATE)) === false)
            {
                return false;
            }

            \fclose($fp);
            @\chmod($file, self::DIR_WRITE_MODE);
            @\unlink($file);
            return true;
        }
        elseif (!\is_file($file) OR ($fp = @\fopen($file, self::FOPEN_WRITE_CREATE)) === false)
        {
            return false;
        }

        \fclose($fp);
        return true;
    }

}
